package com.code.wordhelper.config;

import lombok.extern.slf4j.Slf4j;
import org.jodconverter.core.office.OfficeManager;
import org.jodconverter.local.office.LocalOfficeManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Slf4j
@Configuration
public class OfficeManagerConfig {
    @Autowired
    private LibreOfficeConfig libreOfficeConfig;

    @Bean
    @Primary
    public OfficeManager officeManager() {
        if (libreOfficeConfig.getEnable()) {
            log.info("启动libreoffice...");
            try {
                LocalOfficeManager.Builder builder = LocalOfficeManager.builder();
                builder.officeHome(libreOfficeConfig.getOfficeHome());
                builder.portNumbers(libreOfficeConfig.getPortNumbers());
                builder.taskExecutionTimeout(libreOfficeConfig.getTaskExecutionTimeout().longValue());
                builder.taskQueueTimeout(libreOfficeConfig.getTaskQueueTimeout().longValue());

                OfficeManager INSTANCE = builder.install().build();
                if (!INSTANCE.isRunning()) {
                    INSTANCE.start();
                }

                return INSTANCE;
            } catch (Exception e) {
                log.error("{}", e);
            }
        }
        return null;
    }
}
